<template>

  <div class="container">
    <div class="header">
      <div style="display: flex; justify-content: start;">
        <div v-if="!store.isLogin()">
                  {{ "～～～请登录吧" }}
        <el-button type="warning" @click="openShoppingCar">{{ '登陆' }}</el-button>
        </div>



        <div v-if="store.isLogin()" style="display: inline;">


          <el-dropdown size="small" split-button type="primary">
          欢迎您～<span style="font-size: large; color: bisque;">{{ store.getUser().value.userName }}</span>
          <template #dropdown>
            <el-dropdown-menu>
              <!-- <el-dropdown-item @click="openOrder" >订单</el-dropdown-item>
              <el-dropdown-item @click="openShoppingCar" >购物车</el-dropdown-item>
              <el-dropdown-item @click="openTop" >咱的个人信息</el-dropdown-item> -->
              <el-dropdown-item @click="store.logout()" >退出登陆</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>




          <!-- <el-button type="info" @click="store.logout()">退出登陆</el-button> -->
        </div>
      </div>
      <div style="width: 100px; margin: 0 5%;">
                 <img style="height: 80px;" src="imgs/name.jpg" alt="">
        </div>
      <div v-if="store.isLogin()" style="width: 1000px; margin:0 auto" >


          <el-button type="primary" plain @click="openTop">个人信息</el-button>
          <el-button type="success" plain @click="openShoppingCar">购物车</el-button>
          <el-button type="primary" @click="openOrder">订单</el-button>
          我的金额：: <span style="color: brown;">$ {{ store.getUser().value.account }}</span>
      </div>
      <div >


      </div>
    </div>
    <div class="main">
      <div style="width: 1000px; margin: 0 auto;">
        <el-carousel :interval="5000" arrow="always">
          <el-carousel-item v-for="item in 4" :key="item">
            <img style="width: 1000px" src="imgs/82a438f9-01f4-4395-a5bc-47dec03a23b0.jpg" alt="">
          </el-carousel-item>
        </el-carousel>
      </div>

      <div class="selecter">
        <div class="menue">
          <div class="mname">品牌:</div>
          <div class="mopt">
            <div>
              <el-radio-group @change="brandChage" v-model="phoneAttr.brandId" size="large">
                <el-radio-button v-for="item in brands" :label="item.id">{{ item.msg }}</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>
        <div class="menue">
          <div class="mname">类型:</div>
          <div class="mopt">
              <el-radio-group @change="attrChage" v-model="phoneAttr.typeId">
              <el-radio v-for="item in types" :label="item.id">{{ item.msg }}</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="menue">
          <div class="mname">机身内存:</div>
          <div class="mopt">
            <el-radio-group @change="attrChage" v-model="phoneAttr.disk">
              <el-radio v-for="item in disks" :label="item">{{ item }}GB</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="menue">
          <div class="mname">运行内存:</div>
          <div class="mopt">
            <el-radio-group @change="attrChage" v-model="phoneAttr.memory">
              <el-radio v-for="item in memorys" :label="item">{{ item }}GB</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="menue">
          <div class="mname">价格:</div>
          <div class="mopt">
            <el-radio-group @change="priceChage" v-model="radio">
              <el-radio v-for="item in pirceMargin" :label="item.key">{{ item.value }}</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="menue">
          <div class="mname">颜色:</div>
          <div class="mopt">
            <el-radio-group @change="attrChage" v-model="phoneAttr.colorId">
              <el-radio v-for="item in colors " :label="item.id">{{ item.color }}</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>

      <div style="margin: 0 auto;  margin-top: 10px; width: 50px;"><el-button type="success" @click="reset">重置</el-button></div>

      <div ref="listDiv" class="list">
        <div v-for="item in goodList" @click="detail(item.id)" class="item">
          <img :src="item.coverSrc">
          <p class="name">{{ item.phoneName }} </p>
          <p class="price"> {{ item.price }}</p>
        </div>
      </div>
      <div style="margin-left: 40%;">
        <el-pagination @current-change="pageChange" :total="total" v-model:current-page="currentPage"
          :page-size="pageSize" background :default-current-page="defaultPage" layout="prev, pager, next" />
      </div>
    </div>
  </div>
  <el-backtop :bottom="100">
  </el-backtop>



  <el-drawer size="80%" v-model="toptobottom" title="个人信息页" direction="ttb">
    <div class="person">
      <div class="person-item">
        <div>名字：<el-input v-model="logUser!.userName" style="width: 200px;"></el-input></div>
        <div><div style="display: flex;">
          <div>地址：</div>
          <el-input v-model="province" style="width: 60px;"></el-input>省
          <el-input v-model="city" style="width: 60px;"></el-input>市
          <el-input v-model="prefecture" style="width: 60px;"></el-input>县
        </div>
        </div>
        <div>详细：<el-input v-model="details" style="width: 200px;"></el-input></div>
        <div>手机：<el-input v-model="logUser!.phoneNumber" style="width: 200px;"></el-input></div>
        <div><el-button color="#CCCC" @click="changeAttr">修改</el-button></div>
      </div>
      <div class="person-item">
        <div>旧密码：<el-input v-model="passwdAttr.oldPassword" style="width: 200px;"></el-input></div>
        <div>新密码：<el-input v-model="passwdAttr.newPassword" style="width: 200px;"></el-input></div>
        <div>再确认：<el-input v-model="passwdAttr.rePassword" style="width: 200px;"></el-input></div>
        <div><el-button type="primary" @click="rePasswd">修改</el-button></div>
      </div>
    </div>
    <div style="margin-top: 20px;">历史评论</div>
    <hr>
    <div>
      <el-table :data="commnetsHistory" style="width: 100%">

        <el-table-column label="评论时间" prop="createTime" :formatter="formatterTime"/>
        <el-table-column label="封面" width="180">
          <template #default="scope">
            <img style="width: 80px;" :src="scope.row.coverSrc" alt="">
          </template>
        </el-table-column>

        <el-table-column label="评论内容" prop="msg" />

        <el-table-column label="手机名称" prop="phoneName" />

        <el-table-column label="状态" width="180">
          <template #default="scope">

            <el-tag :type="scope.row.status !== '1' ? '' : 'success'" disable-transitions> {{ scope.row.status ==
              '1' ? '通过' : '未通过' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="danger" @click="deleteComment(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-drawer>



  <el-drawer v-model="drawer2" :direction="direction" size="40%">
    <template #header>
      <h4>我的购物车</h4>
    </template>
    <template #default>
      <div>
        总价：{{ sum }}
      </div>
      <div>

        <el-table :data="filterTableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="手机名" prop="phoneName" />
          <el-table-column label="内存" prop="memory" />
          <el-table-column label="硬盘" prop="disk" />
          <el-table-column label="价格" prop="price" />
          <el-table-column align="right">
            <template #header>
              <el-input v-model="search" size="small" placeholder="搜索" />
            </template>
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button type="primary" @click="confirmClick">购买！</el-button>
      </div>
    </template>
  </el-drawer>








  <el-drawer v-model="drawer" direction="ltr" size="80%">
    <template #header>
      <h4>我的购买记录</h4>
    </template>
    <template #default>
      <div>
        <el-table :data="filterTableData2" style="width: 100%"
        
        >
          <el-table-column label="下单时间" prop="createTime" :formatter="formatterTime" />
          <el-table-column label="封面">
            <template #default="scope">
              <img style="width: 80px;" :src="scope.row.coverSrc" alt="">
            </template>
          </el-table-column>
          <el-table-column label="手机名" prop="phoneName" />
          <el-table-column label="内存" prop="memory" />
          <el-table-column label="硬盘" prop="disk" />
          <el-table-column label="价格" prop="price" />
          <el-table-column label="状态">
            <template #default="scope">


              <el-tag :type="scope.row.status !== '1' ? 'error' : 'success'" disable-transitions> {{ scope.row.status == 0
                ? '未评论' : '已评论' }}</el-tag>

            </template>
          </el-table-column>
          <el-table-column label="物流状态">
            <template #default="scope">


              <el-tag :type="scope.row.logistics === '0' ? 'error' : scope.row.logistics == '1' ? 'success' : 'primary'"
                disable-transitions> {{ scope.row.logistics == '0' ? '未发货' : scope.row.logistics == '1' ? "已发货" : '已签收'
                }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column align="right">
            <template #header>
              <el-input v-model="search" size="small" placeholder="搜索" />
            </template>
            <template #default="scope">
              <el-button type="success" :disabled="!(scope.row.status == 0 && scope.row.logistics === '3')" size="small"
                @click="handleEdit(scope.$index, scope.row)">评论</el-button>
              <el-button type="primary" :disabled="!(scope.row.logistics === '1')" size="small"
                @click="recive(scope.row.id)">收货!</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
  </el-drawer>



  <el-dialog v-model="dialogVisible" title="Tips" width="30%">
    请输入评论内容
    <el-input type="textarea" rows="10" v-model="commnetAttr.comment"></el-input>

    <div class="demo-rate-block">
    <span class="demonstration">打个分吧~</span>
    <el-rate v-model="commnetAttr.rate" />
  </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="sendComment">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>



  <el-dialog
    v-model="resure"
    title="生成订单"
    width="30%"
  >
  <div>
<div>收货人：{{ store.getUser().value.userName }}</div>
<div>收货地址：{{ store.getUser().value.address }}</div>
<div>电话号码：{{ store.getUser().value.phoneNumber }}</div>
  </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resure = false">取消</el-button>
        <el-button type="primary" @click="doPurchase">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>






<script setup lang="ts">
import { onMounted, ref, toRaw } from 'vue'
import { getColors } from '@/api/color';
import { getInfoChildrenByPid } from '@/api/info';
import { getMemoryList, listPhoneByAttr, getDiskList, getPhoneCountByAttr } from '../api/phone'
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import { listShoppingCarApi, delShoppingCar, buyShoopingCar } from '../api/shoppingCar'
import { useUserStore } from '@/stores/counter';
import { listOrder, getUser, changeApi, resetPasswd, reciveApi } from '../api/user'
import { computed } from 'vue'
import { submitComment, getByUserName, deleteCommentApi } from '../api/comment'
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'


const passwdAttr = ref({
  newPassword: '',
  oldPassword: '',
  rePassword: '',
  userName: ''
})
const formatterTime = (row:any, column:any, cellValue:any, index:any) => {
  
  row =  toRaw(row)
  var s =  (row.createTime) as string
          return s.substring(0,10)
        }
const resure = ref()
const multipleSelection = ref<Array<any>>([])

const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
  sum.value = 0
  multipleSelection.value?.forEach(v => {
    sum.value = sum.value + v.price
  })
}

const rePasswd = () => {
  if (passwdAttr.value.newPassword !== passwdAttr.value.rePassword) {
    ElMessage({
      message: '两次不一样',
      type: 'error'
    })
    return
  }
  passwdAttr.value.userName = store.getUser().value.userName
  resetPasswd(passwdAttr.value).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
    } else {
      ElMessage({
        message: res.data.data,
        type: 'error'
      })
    }
  })
}

const store = useUserStore()
const router = useRouter()

const drawer = ref(false)
const drawer2 = ref(false)
const toptobottom = ref(false)
const direction = ref('rtl')
const radio1 = ref('Option 1')

const dialogVisible = ref(false)
const colors = ref()
const brands = ref()
const types = ref()
const memorys = ref()
const disks = ref()
const comment = ref()



const commnetAttr = ref({
  phoneId: '',
  userName: '',
  comment: '',
  orderId: '',
  rate:'0'
})

const pirceMargin = [
  {
    key: 1,
    value: '0~1000'
  },
  {
    key: 2,
    value: '1000~2000',
  },
  {
    key: 3,
    value: '2000~3000',
  },
  {
    key: 4,
    value: '3000~4000',
  },
  {
    key: 5,
    value: '4000~5000',
  },
  {
    key: 6,
    value: '5000~~~'
  }
]

const radio = ref()

const defaultPage = ref(1)
const total = ref(100)
const currentPage = ref()
const pageSize = ref(15)
const goodList = ref()



const phoneAttr = ref({
  colorId: '',
  brandId: '',
  typeId: '',
  memory: '',
  disk: '',
  start: 0,
  offset: pageSize.value,
  min: 0,
  max: 1000000
})


const reset = () => {
  phoneAttr.value.brandId = ''
  phoneAttr.value.typeId = ''
  phoneAttr.value.memory = ''
  phoneAttr.value.disk = ''
  phoneAttr.value.colorId = ''
  phoneAttr.value.brandId = ''
  phoneAttr.value.max = 100000
  phoneAttr.value.min = 0

  radio.value = ''
  listPhoneByAttr(phoneAttr.value).then(res => {
    goodList.value = res.data.data
  })
}
type User = {
  account:number,
  address:string,
  createTime:string,
  password:string,
  phoneNumber:string,
  status:string,
  userName:string,
}
const logUser = ref()




const orderList = ref<Array<any>>()

const tableData = ref<Array<any>>()
const sum = ref(0)

const commnetsHistory = ref<Array<any>>()
const openTop = () => {
  toptobottom.value = true
  getByUserName(store.getUser().value.userName).then(res => {
    console.log(res.data.data);
    commnetsHistory.value = res.data.data
  })
}
const deleteComment = (id: string) => {
  deleteCommentApi(id).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      getByUserName(store.getUser().value.userName).then(res => {
        console.log(res.data.data);
        commnetsHistory.value = res.data.data
      })
    }
  })
}

const changeAttr = () => {
  if (logUser.value!.phoneNumber == '' || logUser.value!.phoneNumber == undefined || logUser.value!.phoneNumber.length < 11) {
    ElMessage({
      message: '长度不够',
      type: 'error'
    })
    return
  }
  if(province.value.length == 0 || city.value.length == 0 || prefecture.value.length == 0 || details.value.length == 0){
    ElMessage({
      message: '请你完善信息',
      type: 'error'
    })
    return;
  }
  logUser.value.address = province.value + '-' + city.value + '-' + prefecture.value +'-'+ details.value 
  changeApi(logUser.value).then(res => {
    if (res.data.code == 200) {
      store.login(res.data.data);
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
    }
  })
}

const recive = (id: string) => {
  reciveApi(id).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      listOrder(store.getUser().value.userName).then(res => {
        orderList.value = res.data.data
      })
    }
  })
}

const search = ref('')

const filterTableData = computed(() =>
  tableData.value!.filter(
    (data: any) =>
      !search.value ||
      data.phoneName.toLowerCase().includes(search.value.toLowerCase())
  )
)

const filterTableData2 = computed(() =>
  orderList.value!.filter(
    (data: any) =>
      !search.value ||
      data.phoneName.toLowerCase().includes(search.value.toLowerCase())
  )
)

const handleDelete = (index: number, row: any) => {
  console.log(index, row.id)
  delShoppingCar({ id: row.id }).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      // sum.value = sum.value - row.price
      listShoppingCarApi(store.getUser().value.userName).then(res => {
        tableData.value = res.data.data
      })
    }
  })
}




var user = toRaw(store.getUser().value)

getUser(user.userName).then(res => {
  store.login(res.data.data)
})


const sendComment = () => {
  dialogVisible.value = false
  submitComment(commnetAttr.value).then(res => {
    if (res.data.code == 200) {
      listOrder(store.getUser().value.userName).then(res => {
        orderList.value = res.data.data
      })
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
    }

  })
}

const handleEdit = (index: any, row: any) => {
  console.log(row);
  dialogVisible.value = true
  commnetAttr.value.phoneId = row.phoneId
  commnetAttr.value.orderId = row.id
}

const province = ref()
const city = ref()
const prefecture = ref()
const details = ref()

if (store.isLogin()) {
  listShoppingCarApi(store.getUser().value.userName).then(res => {
    tableData.value = res.data.data
    multipleSelection.value?.forEach(v => {
      sum.value = sum.value + v.price
    })
  })
  listOrder(store.getUser().value.userName).then(res => {
    orderList.value = res.data.data
  })
  commnetAttr.value.userName = store.getUser().value.userName
  getUser(store.getUser().value.userName).then(res => {
    logUser.value = res.data.data
    province.value = logUser.value?.address.split('-')[0]
    city.value = logUser.value?.address.split('-')[1]
    prefecture.value = logUser.value?.address.split('-')[2]
    details.value = logUser.value?.address.split('-')[3]
  })
}



const openOrder = () => {
  drawer.value = true
  listOrder(store.getUser().value.userName).then(res => {
    orderList.value = res.data.data
  })
}

const doPurchase = () => {
  buyShoopingCar({
    userName: store.getUser().value.userName,
    phones: multipleSelection.value
  }).then(res => {
    if (res.data.code == 200) {
      resure.value = false
      listShoppingCarApi(store.getUser().value.userName).then(res => {
        tableData.value = res.data.data
        sum.value = 0
      })
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      listOrder(store.getUser().value.userName).then(res => {
        orderList.value = res.data.data
      })
    } else {
      ElMessage({
        message: res.data.data,
        type: 'error'
      })
    }

  })
}

function confirmClick() {
resure.value = true
}

const openShoppingCar = () => {
  if (!store.isLogin()) {
    router.push('login')
  }
  drawer2.value = true
}

const detail = (id: any) => {
  router.push({ path: '/phone', query: { id } })
}


listPhoneByAttr(phoneAttr.value).then(res => {
  goodList.value = res.data.data
})
getPhoneCountByAttr(phoneAttr.value).then(res => {
  total.value = res.data.data
})


const brandChage = (id: any) => {
  console.log(id);
  phoneAttr.value.typeId = ''
  getInfoChildrenByPid(id).then(res => {
    types.value = res.data.data
  })
  // search
  listPhoneByAttr(phoneAttr.value).then(res => {
    goodList.value = res.data.data
  })
  getPhoneCountByAttr(phoneAttr.value).then(res => {
    total.value = res.data.data
  })
}
const attrChage = (id: any) => {
  //search
  listPhoneByAttr(phoneAttr.value).then(res => {
    goodList.value = res.data.data
  })
  getPhoneCountByAttr(phoneAttr.value).then(res => {
    total.value = res.data.data
  })
}
const pageChange = (page: number) => {
  phoneAttr.value.start = currentPage.value == undefined ? 0 : ((currentPage.value - 1) * pageSize.value)
  listPhoneByAttr(phoneAttr.value).then(res => {
    goodList.value = res.data.data
  })
  getPhoneCountByAttr(phoneAttr.value).then(res => {
    total.value = res.data.data
  })
}
const priceChage = (id: any) => {
  console.log(id);
  phoneAttr.value.max = id != 6 ? id * 1000 : 100 * 1000
  phoneAttr.value.min = (id - 1) * 1000
  listPhoneByAttr(phoneAttr.value).then(res => {
    goodList.value = res.data.data
  })
  getPhoneCountByAttr(phoneAttr.value).then(res => {
    total.value = res.data.data
  })
}


getInfoChildrenByPid(0).then(res => {
  brands.value = res.data.data
})
getColors().then(res => {
  colors.value = res.data.data
})
getMemoryList().then(res => {
  memorys.value = res.data.data
})
getDiskList().then(res => {
  disks.value = res.data.data
})



function moment(arg0: number) {
throw new Error('Function not implemented.');
}
</script>

<style scoped >
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  height: 120px;

}

.main {
  margin-top: 40px;
  flex: 1
}

.selecter {
  padding-top: 20px;
  width: 990px;
  margin: 0 auto;
  text-align: center;
  display: flex;
  flex-direction: column;
}

.menue {

  display: flex;
  flex-direction: row;
  border: 1px solid #919191;
  height: 80px;
}

.mname {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #d1af95;
  width: 90px;
}

.mopt {
  align-items: center;
  display: flex;
  justify-content: center;
}

.person {
  display: flex;
  flex-direction: row;
}

.person-item {
  width: 50%;

}

/* .box {
  width: 70%;
  margin-left: 15%;
  background-color: blue;
  margin-top: 5%;
} */

.list {
  width: 990px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
}

.item {
  width: 240px;
  margin-left: 10px;
  padding: 20px 30px;
  transition: all .5s;
  margin-bottom: 20px;
}

.item:nth-child(4n) {
  margin-left: 0;
}

.item:hover {
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
  transform: translate3d(0, -4px, 0);
  cursor: pointer;
}

.item img {
  width: 100%;
}

.item .name {
  font-size: 18px;
  margin-bottom: 10px;
  color: #666;
}

.item .price {
  font-size: 22px;
  color: firebrick;
}

.item .price::before {
  content: "$";
  font-size: 14px;
}

.filter {
  display: flex;
  width: 990px;
  margin: 0 auto;
  padding: 50px 30px;
}

.filter a {
  padding: 10px 20px;
  background-color: #f5f5f5;
  color: #666;
  text-decoration: none;
  margin-right: 20px;
}

.filter a:active,
.filter a :focus {
  background: #05943c;
  color: #fff;
}











</style>